package com.samsung.spen.sshare.main.sms;

import java.util.HashMap;
import java.util.Map;

import com.samsung.spen.sshare.R;
import com.samsung.spen.sshare.main.MainActivity;
import com.samsung.spen.sshare.main.UpdateViewSMS;
import com.samsung.spen.sshare.networking.networkservice.SendReceiveService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SendSMSFragment extends Fragment implements OnClickListener, UpdateViewSMS {

	int mNum;
	private Button mBtnPick = null;
	private Button mBtnSend = null;
	private EditText mETContent = null;
	private TextView mTVWifiInfo = null;
	private TextView mTVSMSNumber = null;
	public EditText mETNumber = null;
	private String mPhoneNumber;
	private View view;

	private MainActivity bindedActivity = null;
	private ServiceConnection mServiceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			if(name.getClassName().equals(SendReceiveService.class.getName())){
				bindedActivity.mSendReceiveService = null;
				Toast.makeText(bindedActivity, "service disconnected"+ name.getShortClassName(),
						Toast.LENGTH_SHORT).show();
			}
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			if(name.getClassName().equals(SendReceiveService.class.getName())){
				bindedActivity.mSendReceiveService = ((SendReceiveService.LocalBinder) service)
						.getService();
				Toast.makeText(bindedActivity, "service connected: " + name.getShortClassName(),
						Toast.LENGTH_SHORT).show();
				Log.v(this.getClass().toString(), name.getClassName());
				//use service here
				startServer();
			}
		}
	};

	public final int REQUEST_CODE_PICK_CONTACT = 1;

	public SendSMSFragment newInstance(int num) {
		SendSMSFragment f = new SendSMSFragment();

		Bundle args = new Bundle();
		args.putInt("num", num);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mNum = getArguments() != null ? getArguments().getInt("num") : 1;
		this.bindedActivity = (MainActivity) this.getActivity();
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.v("Fragment", "sendsms oncreateView");
		View v = inflater.inflate(R.layout.main_activity_send_sms, container,
				false);
		this.view = v;
		return v;
	}

	@Override
	public void onActivityCreated(Bundle bundle) {
		super.onActivityCreated(bundle);

		mBtnPick = (Button) view.findViewById(R.id.btn_pick);
		mBtnPick.setOnClickListener(this);
		mBtnSend = (Button) view.findViewById(R.id.btn_send);
		mBtnSend.setOnClickListener(this);
		mETContent = (EditText) view.findViewById(R.id.et_content);
		mETNumber = (EditText) view.findViewById(R.id.et_number);
		mTVWifiInfo = (TextView) view.findViewById(R.id.tv_wifi_info);
		mTVSMSNumber = (TextView) view.findViewById(R.id.tv_sms_number);
		
		mETContent.addTextChangedListener(new TextWatcher() {
			
			String addingText = Constants.INDENTIFICATION_STRING + "#000.000.000.000#11111#";
			SmsManager smsManager = SmsManager.getDefault();
			int number = 1;
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				int size = smsManager.divideMessage(s+addingText).size();
				if(size != number){
					number = size;
					mTVSMSNumber.setText(number + " sms");
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}
	
	@Override
	public void onAttach(Activity activity) {
		((MainActivity)getActivity()).updateViewSMS = this;
		super.onAttach(activity);
	}
	
	@Override
	public void onDestroy() {
		if(bindedActivity.mSendReceiveService!=null){
			bindedActivity.unbindService(mServiceConnection);
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_pick:
			Intent pickIntent = new Intent(Intent.ACTION_PICK,
					Contacts.CONTENT_URI);
			pickIntent.setType(Contacts.CONTENT_TYPE);
			startActivityForResult(pickIntent, REQUEST_CODE_PICK_CONTACT);
			break;
		case R.id.btn_send:
			if(mETNumber.getText() == null || mETNumber.getText().toString().isEmpty()){
				Toast.makeText(bindedActivity, "You need to insert a phone number", Toast.LENGTH_SHORT).show();
			} else {
				bindedActivity.checkTurnOnWifi();
				if(bindedActivity.mSendReceiveService == null){
					bindedActivity.bindService(new Intent(bindedActivity,
							SendReceiveService.class), mServiceConnection,
							Context.BIND_AUTO_CREATE);
				} else {
					startServer();
				}
			}
			break; 
		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		case REQUEST_CODE_PICK_CONTACT:
			if (resultCode == this.getActivity().RESULT_OK) {
				Uri uriContact = data.getData();
				Cursor cursor = this.getActivity().getContentResolver()
						.query(uriContact, null, null, null, null);
				if (cursor.moveToFirst()) {
					String name = cursor.getString(cursor
							.getColumnIndex(Contacts.DISPLAY_NAME));
					String contactID = cursor.getString(cursor
							.getColumnIndex(Contacts._ID));
					Cursor cursorPhone = this
							.getActivity()
							.getContentResolver()
							.query(CommonDataKinds.Phone.CONTENT_URI,
									new String[] { CommonDataKinds.Phone.NUMBER },
									CommonDataKinds.Phone.CONTACT_ID + " = ?",
									new String[] { contactID }, null);
					if (cursorPhone.moveToFirst()) {
						mPhoneNumber = cursorPhone.getString(cursorPhone
								.getColumnIndex(CommonDataKinds.Phone.NUMBER));
					}
					mETNumber.setText(mPhoneNumber);
				}

			}
			break;
		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void update() {
	}
	
	public void startServer(){
		Map map = new HashMap<String, String>();
		map.put(SendReceiveService.PHONE_NUM, mETNumber.getText().toString());
		map.put(SendReceiveService.MSG_CONTENT, mETContent.getText().toString());
		bindedActivity.mSendReceiveService.startServer(SendReceiveService.REQUEST_SEND_SMS, map);
	}

	@Override
	public void updateSMSFragment(String phoneNumber) {
		Log.d("BEBE", "not null co vao day k");
		mPhoneNumber = phoneNumber;
		mETNumber.setText(mPhoneNumber);
		Log.d("BEBE", "not null co vao day k :"+ mPhoneNumber);
	}

}
